#!/usr/bin/env python
# -*- coding: utf-8 -*-
# SQL type wrappers audited by Joshua Kugler, 2008-02-20
"""
This API doesn't correspond specifically to any one database
table. It accesses data as it pertains to vehicles and drivers
that are paired up as mission resources.

Please see drivers.py and vehicles.py for specifics about the
direct database access for these two kinds of resources.
"""

from string import Template
from tack.db import query
from tack.lib import string_app, content_headers, status_codes, json_app
from tack.lib.dicttools import query_to_list
import time
from tack_tmpo.api import drivers
from tack_tmpo.api import vehicles

def get_all_resources(environ, start_response):
    output = {}
    sql = drivers.get_drivers
    rows = query(environ['connection'], sql)
    labels = ['id','name','telephone','address','license_number',
              'license_expiration','license_class','license_endorsements',
              'license_restrictions'] 
    output['drivers'] = query_to_list(rows, labels)
    sql = vehicles.select_all_vehicles
    rows = query(environ['connection'], sql)
    labels = ['id', 'vehicleno', 'capacity', 'type', 'tagno', 'doortype',
              'weight']  
    output['vehicles'] = query_to_list(rows, labels)
    return json_app(output)(environ, start_response)

def get_available_resources(environ, start_response):
    try:
        start = environ['dispatcher.groups']['start']
        throwaway = time.strptime(start, '%Y-%m-%d %H:%M')
        finish = environ['dispatcher.groups']['finish']
        throwaway = time.strptime(finish, '%Y-%m-%d %H:%M')
        try:
            record_id = environ['dispatcher.groups']['record_id']
        except:
            record_id = -1
        output = {}
        sql = Template(drivers.driver_availability).substitute(locals())
        rows = query(environ['connection'], sql)
        labels = ['id','name','telephone','address','license_number',
                  'license_expiration','license_class','license_endorsements',
                  'license_restrictions'] 
        output['drivers'] = query_to_list(rows, labels)
        sql = Template(vehicles.select_available_vehicles).substitute(locals())
        rows = query(environ['connection'], sql)
        labels = ['id', 'vehicleno', 'capacity', 'type', 'tagno', 'doortype',
                  'weight'] 
        output['vehicles'] = query_to_list(rows, labels)
    except:
        start_response(status_codes.error, content_headers.default_plain())
        return ['Error']
    return json_app(output)(environ, start_response)
